<!--长效养护-->
<template>
	<page-meta :page-font-size="baseFontSize + 'rpx'" :root-font-size="baseFontSize + 'rpx'"></page-meta>
	<view class="u-page flex flex-direction">
		<view class="addr flex align-center">
			<view>当前位置</view>
			<view class="location flex-sub text-right">{{ latitude || '未获取' }}, {{ longitude || '未获取' }}</view>
			<view @click="startLocation()" class="refresh">刷新</view>
		</view>
		<scroll-view scroll-y class="form flex-sub main">
			<view class="section">
				<image src="/static/images/base.png" mode="widthFix"></image>
				<text>基础信息</text>
			</view>
			<uni-forms :modelValue="formData" border label-width="16rem">
				<uni-forms-item label="设施名称" name="name">
					<view class="facility-name">{{ facilityName }}</view>
				</uni-forms-item>
				<uni-forms-item label="所属构件" name="name">
					<view class="facility-name">{{ compName }}</view>
					<!-- <uni-data-picker
						placeholder="请选择所属构件"
						popup-title="请选择所属构件"
						:placeholderStyle="placeholderStyle"
						:localdata="dataTree"
						v-model="classes"
						:border="false"
						@change="onchange"
						@nodeclick="onnodeclick"
						@popupopened="onpopupopened"
						@popupclosed="onpopupclosed"
					></uni-data-picker> -->
				</uni-forms-item>
				<uni-forms-item :label="item.label" name="name" v-for="(item, index) in monitorContents" :key="index">
					<uni-easyinput :inputBorder="false" type="text" :value="item.mvalue" placeholder="请输入监测数据" @blur="e => valueChange(e, item)" />
				</uni-forms-item>

				<uni-forms-item label="上传照片" name="name">
					<view class="container">
						<view class="preview-box">
							<view class="preview-list">
								<view class="preview-item" v-for="(item, index) in fileList" :key="index">
									<image style="width: 120upx; height: 120upx" :src="item"></image>
									<uni-icons class="delete-icon" @click="removeImg(index)" type="closeempty" size="10"></uni-icons>
								</view>
								<view class="upload-btn-area"><image v-if="fileList.length < 9" @click="chooseImage" src="/static/images/upload.png" mode="widthFix"></image></view>
							</view>
						</view>
					</view>
				</uni-forms-item>

				<uni-forms-item label="上报内容"><uni-easyinput type="textarea" :inputBorder="false" v-model="reportContent" placeholder="请输入上报内容" /></uni-forms-item>
			</uni-forms>
		</scroll-view>
		<view class="page-footer">
			<button @click="submitReport" class="save-btn cu-btn block bg-blue lg" :disabled="isSubmiting" type="blue">
				<uni-icons type="spinner-cycle" size="20" v-if="isSubmiting"></uni-icons>
				提交
			</button>
		</view>
	</view>
</template>

<script>
import upload from '@/components/upload.vue';
import { reportArtificialApi } from '@/api/system/changxiao.js';
export default {
	components: {
		upload
	},
	data() {
		return {
			dataTree: null,
			formData: {},
			placeholderStyle: {
				fontSize: '14px'
			},
			monitorContents: [],
			latitude: '',
			longitude: '',
			artificialReportId: '',
			detailObj: {},
			projectName: '',
			facilityName: '',
			compName: '',
			reportContent: '',
			fileList: [],
			isSubmiting: false
		};
	},
	computed: {
		baseFontSize() {
			return this.$store.getters.fontSize;
		}
	},
	onLoad(e) {
		console.log(e);
		if (e && e.id) {
			this.artificialReportId = e.id;
			this.projectName = e.projectName;
			this.facilityName = e.facilityName;
			this.monitorContents = e.monitorContentList?.split(',').map(item => {
				return {
					label: item.replace(/\"/g, ''),
					mvalue: ''
				};
			});
			this.compName = e.compName;
		}
	},
	mounted() {
		this.startLocation();
	},
	methods: {
		valueChange(e, item) {
			let { value } = e.detail;

			this.monitorContents = this.monitorContents.map(mitem => {
				if (mitem.label === item.label) {
					mitem.mvalue = value;
				}
				return {
					...mitem
				};
			});
		},
		startLocation() {
			let _this = this;
			uni.startLocationUpdate({
				success: res => {
					//成功的逻辑
					uni.onLocationChange(data => {
						this.latitude = data.latitude.toFixed(6);
						this.longitude = data.longitude.toFixed(6);
					});
				},
				fail: err => {
					console.log(err);
					//失败的逻辑
					//1.wx.showModal引导用户授权
					//2.通过wx.openSetting让用户开启权限
					uni.showModal({
						//引导用户授权
						title: '提示',
						content: '请打开定位权限',
						confirmText: '设置',
						cancelText: '取消',
						showCancel: false,
						success: res => {
							//点击“确认”时打开设置页面
							if (res.confirm) {
								uni.openSetting({
									//打开设置页面让用户选择权限
									success: res => {
										console.log(res);
										if (res.authSetting['scope.userLocation'] == true) {
											uni.onLocationChange(data => {
												//实时获取用户最新的经纬度信息
												console.log(data);
											});
										}
									}
								});
							} else {
								//取消打开设置授权页面
								uni.showToast({
									title: '取消授权',
									icon: 'none'
								});
							}
						}
					});
				}
			});
		},
		removeImg(index) {
			this.fileList.splice(index, 1);
		},
		submitReport() {
			if (this.isSubmiting) {
				return;
			}
			if (this.fileList.length == 0) {
				uni.showToast({
					title: '请上传图片',
					icon: 'error',
					duration: 2000
				});
				return;
			}
			this.isSubmiting = true;
			reportArtificialApi({
				artificialReportId: this.artificialReportId, // id
				latitude: this.latitude, // 坐标
				longitude: this.longitude, // 坐标
				monitorContents: this.monitorContents.map(item => {
					let { label, mvalue } = item;
					return {
						[`"${label}"`]: mvalue
					};
				}),
				images: this.fileList, // 图片最多9个
				reportContent: this.reportContent // 上报内容
			})
				.then(res => {
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				})
				.finally(() => {
					this.isSubmiting = false;
				});
		},
		chooseImage() {
			uni.chooseImage({
				count: 9,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: res => {
					const tempFilePaths = res.tempFilePaths;
					this.uploadImage(tempFilePaths);
				}
			});
		},
		uploadImage(images) {
			const count = images.length;
			let currentIndex = 0;
			for (let i = 0; i < count; i++) {
				uni.uploadFile({
					url: 'https://ruoyi.51wephone.cn/admin-api/infra/file/upload', //上传接口地址
					filePath: images[i],
					name: 'file',
					formData: {},
					header: {
						Authorization: `Bearer ${uni.getStorageSync('ACCESS_TOKEN')}`
					},
					success: res => {
						currentIndex++;
						const data = JSON.parse(res.data);
						if (currentIndex >= count) {
							uni.showToast({
								title: '上传成功',
								icon: 'success',
								duration: 2000
							});
						}
						this.fileList.push(JSON.parse(res.data).data);
					}
				});
			}
		}
	}
};
</script>
<style lang="scss">
page {
	height: 100%;
}
</style>
<style lang="scss" scoped>
@import '@/static/scss/form.scss';
.u-page {
	font-size: 2.8rem;
}
.container {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: flex-start;
}

.upload-box {
	margin-bottom: 20px;
}

.preview-box {
	flex: 1;
}

.preview-list {
	display: flex;
	flex-wrap: wrap;
	justify-content: flex-start;
	align-items: center;

	.upload-btn-area {
		width: 120upx;
		height: 120upx;
		margin-right: 10px;
		margin-bottom: 10px;
		border: 1upx dashed #f2f2f2;
		border-radius: 12upx;
		box-sizing: border-box;
		display: flex;
		justify-content: center;
		align-items: center;

		:deep(.uni-icons) {
			font-size: 80upx !important;
		}
	}
}

.preview-item {
	box-sizing: border-box;
	width: 120upx;
	height: 120upx;
	margin-right: 10px;
	margin-bottom: 10px;
	position: relative;

	.delete-icon {
		position: absolute;
		right: -8upx;
		top: -8upx;
		background: rgba(0, 0, 0, 0.2);
		border-radius: 50%;
		padding: 8upx;

		.uni-icons {
			font-size: 30upx !important;
		}
	}
}

.preview-item image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}
.facility-name {
	padding-left: 10upx;
	padding-top: 5upx;
}
</style>
